﻿using RPAVIEW.views.EditPage.flows;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using System;
using System.Collections.Concurrent;
using System.Windows;

namespace RPAVIEW.util {
    /// <summary>
    /// 用于前端ui对RPA变量的一些操作，包括变量定义，存取，添加，删除等
    /// </summary>
    public class ParamUtil {
        public static T GetCurrentParam<T>()where T : BaseParam { 
            FlowEditWindow fe = WindowUtil.GetWindow<FlowEditWindow>();
            T t = fe.DataContext as T;
            return t;
        }

        public static ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> GetGlobalData() { 
            return (ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>)WindowUtil.GetCurrentEditHome().DataContext;
        }

        //定义变量
        public static void DefineVar(string varPos, string varName, RPAVariable value, Type varType, params string[] preRemove) { 
            ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> gd = GetGlobalData();
            RPAVariableDefineWrapper remove;
            foreach(string name in preRemove) { 
                RemoveVar(name);
            }
            gd[DefaultContents.RUNNING_PARAM].TryRemove(varName, out remove);
            var custVar = new RPAVariableDefineWrapper(value, varType);
            gd[varPos].TryAdd(varName, custVar);
            FlowEditWindow editWin = WindowUtil.GetWindow<FlowEditWindow>();
            if(editWin != null) { 
                editWin.AddDefinedVar(custVar);
            }
        }

        public static void DefineVar(string varPos, string varName, Type varType,params string[] preRemove) { 
            DefineVar(varPos, varName, null, varType, preRemove);
        }

        public static void RemoveVar(string varName) { 
            ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> gd = GetGlobalData();
            RPAVariableDefineWrapper remove;
            gd[DefaultContents.RUNNING_PARAM].TryRemove(varName, out remove);
            gd[DefaultContents.GLOBLE_PARAM].TryRemove(varName, out remove);
        }

        public static T GetAppGlobleVar<T>(string key){
            App app = Application.Current as App;
            return (T)app.GetGlobalVar(key);
        }

        public static void SetAppGlobalVar(string key, object value) { 
            App app = Application.Current as App;
            app.SetGlobalVar(key, value);
        }
    }
}
